package com.linkoog.devtools.generate.method_creater.dialog;

import com.intellij.notification.Notification;
import com.intellij.notification.NotificationDisplayType;
import com.intellij.notification.NotificationGroup;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.ValidationInfo;
import com.linkoog.devtools.generate.method_creater.domain.ControllerMethodVo;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.util.function.Consumer;

public class ControllerMethodDialog extends DialogWrapper {

    private static NotificationGroup notificationGroup;
    static {
        notificationGroup = new NotificationGroup("DevTools.CodeGen.ControllerMethod",  NotificationDisplayType.BALLOON, true);
    }

    private Project project;
    private JPanel myMainPanel;

    private final ControllerMethodPanel controllerMethodPanel;

    private Consumer<ControllerMethodVo> callback;

    public ControllerMethodDialog(Project project,@NotNull Consumer<ControllerMethodVo> callback) {
        super(project,true);
        this.project = project;
        this.callback = callback;

        setTitle("创建Http方法");
        setResizable(false);
        myMainPanel.setPreferredSize(new Dimension(620, 450));

        controllerMethodPanel = new ControllerMethodPanel();
        myMainPanel.add(controllerMethodPanel.getMyMainPanel(), BorderLayout.NORTH);


        init();
    }

    @Override
    public void doCancelAction() {
        super.doCancelAction();
    }

    @Override
    protected @Nullable ValidationInfo doValidate() {
        return null;
    }

    @Override
    protected void doOKAction() {
        super.doOKAction();
        if (callback != null){
            try {
                callback.accept(getConfig());
            }catch (Exception e){
                SwingUtilities.invokeLater(() -> showErrorMessage(project, e.getMessage()));
            }
        }
    }

    public ControllerMethodVo getConfig(){
        ControllerMethodVo vo = new ControllerMethodVo();
        controllerMethodPanel.getConfig(vo);
        return vo;
    }

    @Override
    public JPanel createCenterPanel() {
        return myMainPanel;
    }

    public JPanel getMyMainPanel() {
        return myMainPanel;
    }

    private void showErrorMessage(Project project, String errorMsg) {
        Notification error = notificationGroup.createNotification(errorMsg, NotificationType.INFORMATION);
        Notifications.Bus.notifyAndHide(error, project);
    }
}
